﻿using MediatR;
using SmartCity.ProcessEngine.API.Write.Application.Commands.FormDetails;
using SmartCity.ProcessEngine.Domain;
using SmartCity.ProcessEngine.Errorcode;
using SmartCity.ProcessEngine.Infrastructure.Interfaces;
using Yitter.IdGenerator;

namespace SmartCity.ProcessEngine.API.Write.Application.CommandHandlers.FormDetails
{
    public class FormDetailCreateCommandHandler:IRequestHandler<FormDetailCreateCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<WF_FormDetail> detailRep;
        private readonly ILogger<FormDetailCreateCommandHandler> logger;
        public FormDetailCreateCommandHandler(IBaseRepository<WF_FormDetail> detailRep, ILogger<FormDetailCreateCommandHandler> logger)
        {
            this.detailRep = detailRep;
            this.logger = logger;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回批量操作任务</returns>
        public async Task<ApiResult<int>> Handle(FormDetailCreateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.code = ApiEnum.AddSuccess;
            result.message = "批量添加成功";

            //foreach (var formDetail in request.FormDetails)
            //{
            //    formDetail.DetailId = YitIdHelper.NextId().ToString();
            //}

            //事务
            using (var tran = detailRep.DB.Database.BeginTransaction())
            {
                try
                {
                    //判断-传进来的集合的数量必须大于0 但是对于业务来说字段至少要两个
                    if (request.FormDetails.Count < 2)
                    {
                        throw new Exception("表单明细中至少要有2条数据");
                    }
                    int count = request.FormDetails.Count(x => string.IsNullOrEmpty(x.FieIdDesc) || string.IsNullOrEmpty(x.FieIdName) || string.IsNullOrEmpty(x.FieIdType) || string.IsNullOrEmpty(x.FieldContorl));
                    if(count > 0)
                    {
                        throw new Exception("表单明细中 的描述、名称、类型、对应的都不能为空");
                    }

                    //找到旧的数据 然后删除(逻辑删除)
                    var list = detailRep.GetAll().Where(x => x.FormNo == request.FormDetails[0].FormNo && !x.IsDeleted).ToList();
                    //逻辑删除旧的数据
                    list.ForEach(x =>
                    {
                        x.IsDeleted = true;
                    });
                    await detailRep.UpdateRangeAsync(list);

                    //添加
                    request.FormDetails.ForEach(x =>
                    {
                        x.DetailId = YitIdHelper.NextId().ToString();
                    });

                    //批量添加表单明细表
                    await detailRep.AddRangeAsync(request.FormDetails);

                    //提交事务 后续不能再写代码
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    result.code = ApiEnum.AddFail;
                    result.message = ex.Message;
                    logger.LogError("批量添加表单明细时报错:"+ex.Message);
                    //回滚事务 后续不能再写代码
                    tran.Rollback();
                }
            }
            return await Task.FromResult(result);
        }
    }
}
